package com.nanychuan.blogback.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.nanychuan.blogback.mapper.UserMapper;
import com.nanychuan.blogback.pojo.User;
import com.nanychuan.blogback.service.UserService;
import com.nanychuan.blogbase.exception.BlogEnums;
import com.nanychuan.blogbase.exception.BlogException;
import com.nanychuan.blogbase.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 往
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(User user, String code, String rightCode) {
        //校验验证码是否正确
        if (!rightCode.equals(code)){
            throw new BlogException(BlogEnums.USER_LOGIN_CODE);
        }
        //对用户密码进行加密
        String password = user.getPassword();
        password = MD5Util.getMD5(password);
        user.setPassword(password);
        //校验用户名和密码
        List<User> userList = userMapper.select(user);
        if (userList.size()==0){
            throw new BlogException(BlogEnums.USER_LOGIN_USER);
        }
        return userList.get(0);
    }

    @Override
    public void verifyOldPwd(String oldPassword, User user) {
        //将输入的旧密码进行加密
        oldPassword = MD5Util.getMD5(oldPassword);
        //获取当前用户的原始密码
        String password = user.getPassword();
        //比价原始密码是否与输入的密码相等
        if (!password.equals(oldPassword)){
            throw new BlogException(BlogEnums.USER_UPDATE_PASSWORD);
        }
    }

    //异步修改用户信息
    @Override
    public void updateUser(User user) {
        //给新密码进行加密
        user.setPassword(MD5Util.getMD5(user.getPassword()));

        //通过主键修改用户信息
        int count = userMapper.updateByPrimaryKeySelective(user);
        if (count==0){
            throw new BlogException(BlogEnums.USER_UPDATE_INFORMATION);
        }
    }

    @Override
    public User blogLogin(User user) {
        //校验用户名和密码
        List<User> userList = userMapper.select(user);
        if (userList.size()==0){
            throw new BlogException(BlogEnums.USER_LOGIN_USER);
        }
      return userList.get(0);
    }
}
